/* eslint-disable @typescript-eslint/no-var-requires */
// import jws from 'jws';
const jws = require('jws');
const jwt = require('jsonwebtoken');
export const secret = '*&S^&@&$csuxzy';
const expiresIn = 60 * 60;

// 获取token的方法
export const getToken = (paload: IAnyObject) => {
  const token = jwt.sign(paload, secret, { expiresIn });
  return token;
}

// 通过jws获取token的相关信息
export const decodeToken = (jwt: string, options?: IAnyObject) => {
  options = options || {};
  const decoded = jws.decode(jwt, options);
  if (!decoded) { return null; }
  let payload = decoded.payload;

  //try parse the payload
  if(typeof payload === 'string') {
    try {
      const obj = JSON.parse(payload);
      if(obj !== null && typeof obj === 'object') {
        payload = obj;
      }
    } catch (e) { 
      console.log(e)
    }
  }

  //return header if `complete` option is enabled.  header includes claims
  //such as `kid` and `alg` used to select the key within a JWKS needed to
  //verify the signature
  if (options.complete === true) {
    return {
      header: decoded.header,
      payload: payload,
      signature: decoded.signature
    };
  }
  return payload;
};
